﻿using System.Text;
using Newtonsoft.Json;

namespace TenantSecurityProvider.Utils;

/// <summary>
/// Http 请求工具类
/// </summary>
public abstract class HttpUtils
{
    /// <summary>
    /// HttpClient 实例
    /// </summary>
    private static readonly HttpClient HttpClient;

    /// <summary>
    /// 静态构造函数
    /// </summary>
    static HttpUtils()
    {
        HttpClient = new HttpClient();
        HttpClient.Timeout = new TimeSpan(0, 0, 30);
    }

    /// <summary>
    /// 发起 Post 请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    public static async Task<T> PostAsync<T>(string url, string content = null)
    {
        var stringContent = string.IsNullOrWhiteSpace(content)
            ? null
            : new StringContent(content, Encoding.UTF8, "application/json");

        using var response = await HttpClient.PostAsync(url, stringContent);
        var str = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(str);
    }
}
